package com.link.base.base.member.controller;

import com.link.base.base.member.model.MchMpPay;
import com.link.base.base.member.model.MpMember;
import com.link.base.base.member.model.MpWeixinPay;
import com.link.base.base.member.service.MpMemberService;
import com.link.base.base.saleactivity.service.AccntCampMonitorService;
import com.link.core.cllog.LCLogger;
import com.link.base.wechat.payment.util.PayUtils;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.KeyGenerateService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * 会员
 *
 * @author: 路江
 * @date 2018-10-22
 */
@Controller
@RequestMapping("/link/mpmember")
public class MpMemberController extends BasicController<MpMember> {

    @Resource
    private KeyGenerateService keyGenerateService;

    @Resource
    private MpMemberService mpmemberService;

    @Resource
    private AccntCampMonitorService accntCampMonitorService;

    @Override
    public BasicService<MpMember> getBasicService() throws Exception {
        return mpmemberService;
    }

    /**
     * 统一下单 (小程序支付)
     *
     * @author 路江
     * @date 2018-10-22
     */
    @RequestMapping(value = "/orderMpPay")
    @ResponseBody
    public Map<String,Object> orderMpPay(@RequestBody MpWeixinPay mpWeixinPay, HttpServletRequest request, HttpServletResponse response) {
        Map<String,Object> result = new HashMap<>(16);
        try {
            result = mpmemberService.orderMpPay(mpWeixinPay,request);
            result.put("success",true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("msg",e.getMessage());
            result.put("success",false);
        }

        return result;
    }

    /**
     * 支付回调
     *
     * @author 路江
     * @date 2018-10-22
     */
    @RequestMapping(value = "/notify_url")
    @ResponseBody
    public void notifyUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(request.getInputStream()));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            //解析并给微信发回收到通知确认
            Map map =  PayUtils.doXMLParse(sb.toString());
            String returnCode = "";
            String retuCode = "return_code";
            if (null != map.get(retuCode)) {
                returnCode = map.get(retuCode).toString();
            }
            String success = "SUCCESS";
            if (success.equals(returnCode)) {
                String resultCode = "";
                String resCode = "result_code";
                if (null != map.get(resCode)) {
                    resultCode = map.get(resCode).toString();
                }
                if (success.equals(resultCode)) {
                    String sign = mpmemberService.createSign(map);

                    String originSign = "";
                    String s = "sign";
                    if (null != map.get(s)) {
                        originSign = map.get(s).toString();
                    }
                    if (sign.equals(originSign)) {
                        //签名一致，保存支付流水
                        //改变付款状态
                        try {
                            mpmemberService.orderPayUpdate(map);
                        } catch (Exception e) {
                            String resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                                    + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                            writeMessageToResponse(response,resXml);
                        }
                        String resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                                + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                        writeMessageToResponse(response,resXml);
                    } else {
                        String resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                                + "<return_msg><![CDATA[签名校验失败]]></return_msg>" + "</xml> ";
                        writeMessageToResponse(response,resXml);
                    }
                } else {
                    String resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                            + "<return_msg><![CDATA[返回通知失败]]></return_msg>" + "</xml> ";
                    writeMessageToResponse(response,resXml);
                }
            } else {
                String resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                        + "<return_msg><![CDATA[返回通知失败]]></return_msg>" + "</xml> ";
                writeMessageToResponse(response,resXml);
            }
        } catch (Exception e) {
            String resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[返回通知失败]]></return_msg>" + "</xml> ";
            writeMessageToResponse(response,resXml);
        } finally {
            if (br != null) {
                br.close();
            }
        }
    }

    /**
     * 返回通知微信服务器
     *
     * @author 路江
     * @date 2018-10-22
     * @param response HttpServletResponse
     * @param resXml 返回内容
     */
    protected void writeMessageToResponse(HttpServletResponse response, String resXml) throws Exception {
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
        } catch (IOException e) {
            LCLogger.withException(e);
        } finally {
            if (out != null) {
                out.close();
            }

        }
    }

    /**
     * 企业支付
     *
     * @author 路江
     * @date 2018-10-22
     * @param mchMpPay
     * @param request
     * @return
     */
    @RequestMapping(value = "/mchMpPay")
    @ResponseBody
    public Map<String,Object> mchMpPay(@RequestBody MchMpPay mchMpPay, HttpServletRequest request) {
        Map<String,Object> result = new HashMap<>(16);
        try {
            Map<String,Object> returnResult = mpmemberService.mchMpPay(mchMpPay,request);
            result.put("redMoney", returnResult.get("redMoney"));
            result.put("success",true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("msg",e.getMessage());
            result.put("success",false);
        }
        return result;
    }

    /**
     * 查询企业付款
     *
     * @author 路江
     * @date 2018-10-22
     */
    @RequestMapping(value = "/queryPayResult")
    @ResponseBody
    public Map<String,Object> queryPayResult(@RequestBody MchMpPay mchMpPay, HttpServletRequest request) {
        Map<String,Object> result = new HashMap<>(16);
        try {
            result = mpmemberService.queryPayResult(mchMpPay,request);
            result.put("success",true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success",false);
        }
        return result;
    }

    /**
     * 查询会员信息
     *
     * @author wangdawei
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryMemInfo")
    @ResponseBody
    public Map<String,Object> queryMemInfo(Long id, HttpServletRequest request) {
        Map<String,Object> result = new HashMap<>(8);
        try {
            result = mpmemberService.queryMemInfo(id);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("msg",e.getMessage());
            result.put("success",false);
        }
        return result;
    }
}
